package co.gov.medellin.ssti.sub.web.action;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Collection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.WebServiceException;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import co.gov.medellin.ssti.sub.model.service.SisbenService;
import co.gov.medellin.ssti.sub.model.service.ws.vivanto.artifacts.ParametrosSalidaVictima;
import co.gov.medellin.ssti.sub.model.service.ws.vivanto.client.VivantoConsumer;
import co.gov.medellin.ssti.sub.model.vo.BeneficiarioSisbenVO;
import co.gov.medellin.ssti.sub.web.form.ConsultasExternasForm;

@Component
public class ConsultasExternasAction extends Action {
	@Autowired
	VivantoConsumer vivantoConsumer;
	@Autowired
	SisbenService sisbenServiceImpl;

	public static final String SISBEN = "SISBEN";
	public static final String GRUPO_FAMILIAR_SISBEN = "GRUPO_FAMILIAR_SISBEN";
	public static final String CONSULTAR_VICTIMA_VIVANTO = "CONSULTAR_VICTIMA_VIVANTO";
	public static final String CONSULTA_GRUPO_FAMILIAR_IDENTIFICADOR_VIVANTO = "CONSULTA_GRUPO_FAMILIAR_IDENTIFICADOR_VIVANTO";
	public static final String CONSULTA_GRUPO_FAMILIAR_RADICADO_VIVANTO = "CONSULTA_GRUPO_FAMILIAR_RADICADO_VIVANTO";

	public static final String UNKNOWN_HOST = "No se puede conectar a vivanto.";

	private final String NO_RESULTS = "No hay resultados";

	/**
	 * This is the main action called from the Struts framework.
	 * 
	 * @param mapping
	 *            The ActionMapping used to select this instance.
	 * @param form
	 *            The optional ActionForm bean for this request.
	 * @param request
	 *            The HTTP Request we are processing.
	 * @param response
	 *            The HTTP Response we are processing.
	 * @return
	 * @throws java.io.IOException
	 * @throws javax.servlet.ServletException
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {

		ConsultasExternasForm formBean = (ConsultasExternasForm) form;

		if (SISBEN.equals(formBean.getConsulta())) {
			BeneficiarioSisbenVO beneficiarioCriteriaVo = new BeneficiarioSisbenVO();
			// criterios
			if (formBean.getPrimerNombre() != null
					&& !formBean.getPrimerNombre().isEmpty()) {
				if (formBean.getPrimerNombre().length() < 2) {
					formBean.setMessage("Nombre muy corto.");
					return mapping.findForward("success");
				}
				beneficiarioCriteriaVo.setPrimerNombre(formBean
						.getPrimerNombre());
			}
			if (formBean.getSegundoNombre() != null
					&& !formBean.getSegundoNombre().isEmpty()) {
				if (formBean.getSegundoNombre().length() < 2) {
					formBean.setMessage("Segundo nFombre muy corto.");
					return mapping.findForward("success");
				}
				beneficiarioCriteriaVo.setSegundoNombre(formBean
						.getSegundoNombre());
			}
			if (formBean.getPrimerApellido() != null
					&& !formBean.getPrimerApellido().isEmpty()) {
				if (formBean.getPrimerApellido().length() < 2) {
					formBean.setMessage("Apellido muy corto.");
					return mapping.findForward("success");
				}
				beneficiarioCriteriaVo.setPrimerApellido(formBean
						.getPrimerApellido());
			}
			if (formBean.getSegundoApellido() != null
					&& !formBean.getSegundoApellido().isEmpty()) {
				if (formBean.getSegundoApellido().length() < 2) {
					formBean.setMessage("Segundo apellido muy corto.");
					return mapping.findForward("success");
				}
				beneficiarioCriteriaVo.setSegundoApellido(formBean
						.getSegundoApellido());
			}
			if (formBean.getNumeroDocumento() != null
					&& !formBean.getNumeroDocumento().isEmpty()) {
				beneficiarioCriteriaVo.setNumeroDocumento(formBean
						.getNumeroDocumento());
			}
			if (formBean.getTipoDocumento() != null
					&& !formBean.getTipoDocumento().isEmpty()) {
				beneficiarioCriteriaVo.setTipoDocumento(formBean
						.getTipoDocumento());
			}
			if (formBean.getFechaNacimiento() != null
					&& !formBean.getFechaNacimiento().isEmpty()) {
				beneficiarioCriteriaVo.setFechaNacimiento(formBean
						.getFechaNacimiento());
			}

			try {
				Collection<BeneficiarioSisbenVO> beneficiario = sisbenServiceImpl
						.findBeneficiarioByCriteria(beneficiarioCriteriaVo);
				formBean.setSalidaSisben(beneficiario);
				if (beneficiario == null || beneficiario.isEmpty()) {
					formBean.setMessage(NO_RESULTS);
				}
			} catch (Exception e) {
				if (e.getMessage() != null) {
					formBean.setMessage(e.getMessage());
				} else {
					e.printStackTrace();
				}
			}
		} else if (GRUPO_FAMILIAR_SISBEN.equals(formBean.getConsulta())) {
			Collection<BeneficiarioSisbenVO> grupo = sisbenServiceImpl
					.findGrupoFamiliar(formBean.getTipoDocumento(),
							formBean.getNumeroDocumento());
			formBean.setSalidaSisben(grupo);
			if (grupo == null || grupo.isEmpty()) {
				formBean.setMessage(NO_RESULTS);
			}
		} else if (CONSULTAR_VICTIMA_VIVANTO.equals(formBean.getConsulta())) {
			ParametrosSalidaVictima salida;
			try {
				salida = vivantoConsumer.consultarVictima(formBean
						.getNumeroDocumento());
				formBean.setParametrosSalidaVictimaVivanto(salida);
			} catch (WebServiceException e) {
				if (e.getCause() != null
						&& e.getCause() instanceof UnknownHostException) {
					formBean.setMessage(UNKNOWN_HOST);
				} else {
					formBean.setMessage(e.getMessage());
				}
			} catch (UnknownHostException e) {
				formBean.setMessage(UNKNOWN_HOST);
			} catch (IOException e) {
				formBean.setMessage(e.getMessage());
			}
		} else if (CONSULTA_GRUPO_FAMILIAR_IDENTIFICADOR_VIVANTO
				.equals(formBean.getConsulta())) {
			ParametrosSalidaVictima salida;
			try {
				salida = vivantoConsumer
						.consultaGrupoFamiliarIdentificador(formBean
								.getNumeroDocumento());
				formBean.setParametrosSalidaVictimaVivanto(salida);
			} catch (WebServiceException e) {
				if (e.getCause() != null
						&& e.getCause() instanceof UnknownHostException) {
					formBean.setMessage(UNKNOWN_HOST);
				} else {
					formBean.setMessage(e.getMessage());
				}
			} catch (UnknownHostException e) {
				formBean.setMessage(UNKNOWN_HOST);
			} catch (IOException e) {
				formBean.setMessage(e.getMessage());
			}
		} else if (CONSULTA_GRUPO_FAMILIAR_RADICADO_VIVANTO.equals(formBean
				.getConsulta())) {
			ParametrosSalidaVictima salida;
			try {
				salida = vivantoConsumer.consultaGrupoFamiliarRadicado(formBean
						.getNumeroDocumento());
				formBean.setParametrosSalidaVictimaVivanto(salida);
			} catch (WebServiceException e) {
				if (e.getCause() != null
						&& e.getCause() instanceof UnknownHostException) {
					formBean.setMessage(UNKNOWN_HOST);
				} else {
					formBean.setMessage(e.getMessage());
				}
			} catch (UnknownHostException e) {
				formBean.setMessage(UNKNOWN_HOST);
			} catch (IOException e) {
				formBean.setMessage(e.getMessage());
			}
		}

		return mapping.findForward("success");
	}
}
